﻿using System;
using System.Data.SQLite;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebForm.Helper;

namespace WebForm
{
    public partial class UserManage : Page
    {
        private string _sortExpression = string.Empty;
        private string _searchName = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        
        protected void btnAddUser_Click(object sender, EventArgs e)
        {
	        var name = txtAddName.Text.Trim();
	        var email = txtAddEmail.Text.Trim();
	        var password = txtAddPassword.Text.Trim();
	        var gender = ddlAddGender.SelectedValue;
	        var phoneNumber = txtAddPhoneNumber.Text.Trim();
	        var dateOfBirth = txtAddDateOfBirth.Text.Trim();
	        var sql = "INSERT INTO Users (Name, Email,Password, Gender, PhoneNumber, DateOfBirth) VALUES (@Name, @Email,@Password, @Gender, @PhoneNumber, @DateOfBirth)";
	        DbHelper.ExecuteNonQuery(
		        sql,
		        new SQLiteParameter("@Name", name),
		        new SQLiteParameter("@Email", email),
		        new SQLiteParameter("@Password", password),
		        new SQLiteParameter("@Gender", gender),
		        new SQLiteParameter("@PhoneNumber", phoneNumber),
		        new SQLiteParameter("@DateOfBirth", dateOfBirth)
	        );
	        txtAddName.Text = "";
	        txtAddEmail.Text = "";
	        ddlAddGender.SelectedIndex = 0;
	        txtAddPhoneNumber.Text = "";
	        txtAddDateOfBirth.Text = "";
	        BindGrid();
        }
        
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            _sortExpression = e.SortExpression;
            if (ViewState["SortDirection"] != null)
            {
                _sortExpression += " " + ViewState["SortDirection"];
            }
            if (ViewState["SortDirection"] == null || ViewState["SortDirection"].ToString() == "ASC")
            {
                ViewState["SortDirection"] = "DESC";
            }
            else
            {
                ViewState["SortDirection"] = "ASC";
            }
            BindGrid();
        }
        
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var userId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex]?.Value);
            var sql = "DELETE FROM Users WHERE ID = @UserID";
            DbHelper.ExecuteNonQuery(
                sql,
                new SQLiteParameter("@UserID", userId)
            );
            BindGrid();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var userId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex]?.Value);
            var row = GridView1.Rows[e.RowIndex];
            var name = ((TextBox)row.FindControl("txtName")).Text.Trim();
            var email = ((TextBox)row.FindControl("txtEmail")).Text.Trim();
            var gender = ((DropDownList)row.FindControl("ddlGenderEdit")).SelectedValue;
            var phoneNumber = ((TextBox)row.FindControl("txtPhoneNumberEdit")).Text.Trim();
            var dateOfBirth = ((TextBox)row.FindControl("txtDateOfBirthEdit")).Text.Trim();
            var sql = "UPDATE Users SET Name = @Name, Email = @Email, Gender = @Gender, PhoneNumber = @PhoneNumber, DateOfBirth = @DateOfBirth WHERE ID = @UserID";
            DbHelper.ExecuteNonQuery(
                sql,
                new SQLiteParameter("@Name", name),
                new SQLiteParameter("@Email", email),
                new SQLiteParameter("@Gender", gender),
                new SQLiteParameter("@PhoneNumber", phoneNumber),
                new SQLiteParameter("@DateOfBirth", dateOfBirth),
                new SQLiteParameter("@UserID", userId)
            );
            GridView1.EditIndex = -1;
            BindGrid();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGrid();
        }
        
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
	        GridView1.EditIndex = -1;
	        BindGrid();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        private void BindGrid()
        {
            string sql = "SELECT ID, Name, Gender, Email, PhoneNumber, DateOfBirth FROM Users";
            if (!string.IsNullOrEmpty(_searchName))
            {
                sql += " WHERE Name LIKE @SearchName";
            }
            if (!string.IsNullOrEmpty(_sortExpression))
            {
                sql += " ORDER BY " + _sortExpression;
            }
            var dataSet = DbHelper.ExecuteDataSet(sql, new SQLiteParameter("@SearchName", "%" + _searchName + "%"));
            GridView1.DataSource = dataSet.Tables[0];
            GridView1.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            _searchName = txtSearchName.Text.Trim();
            BindGrid();
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            _searchName = string.Empty;
            txtSearchName.Text = string.Empty;
            BindGrid();
        }
    }
}
